{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "ef597741-3211-4ecc-92f7-f58023ee237e",
      "metadata": {
        "id": "ef597741-3211-4ecc-92f7-f58023ee237e"
      },
      "source": [
        "# LangChain Academy\n",
        "\n",
        "Welcome to LangChain Academy!\n",
        "\n",
        "## Context\n",
        "\n",
        "At LangChain, we aim to make it easy to build LLM applications. One type of LLM application you can build is an agent. There’s a lot of excitement around building agents because they can automate a wide range of tasks that were previously impossible.\n",
        "\n",
        "In practice though, it is incredibly difficult to build systems that reliably execute on these tasks. As we’ve worked with our users to put agents into production, we’ve learned that more control is often necessary. You might need an agent to always call a specific tool first or use different prompts based on its state.\n",
        "\n",
        "To tackle this problem, we’ve built [LangGraph](https://langchain-ai.github.io/langgraph/) — a framework for building agent and multi-agent applications. Separate from the LangChain package, LangGraph’s core design philosophy is to help developers add better precision and control into agent workflows, suitable for the complexity of real-world systems.\n",
        "\n",
        "## Course Structure\n",
        "\n",
        "The course is structured as a set of modules, with each module focused on a particular theme related to LangGraph. You will see a folder for each module, which contains a series of notebooks. A video will accompany each notebook to help walk through the concepts, but the notebooks are also stand-alone, meaning that they contain explanations and can be viewed independent of the videos. Each module folder also contains a `studio` folder, which contains a set of graphs that can be loaded into [LangGraph Studio](https://github.com/langchain-ai/langgraph-studio), our IDE for building LangGraph applications.\n",
        "\n",
        "## Setup\n",
        "\n",
        "Before you begin, please follow the instructions in the `README` to create an environment and install dependencies.\n",
        "\n",
        "## Chat models\n",
        "\n",
        "In this course, we'll be using [Chat Models](https://python.langchain.com/v0.2/docs/concepts/#chat-models), which do a few things take a sequence of messages as inputs and return chat messages as outputs. LangChain does not host any Chat Models, rather we rely on third party integrations. [Here](https://python.langchain.com/v0.2/docs/integrations/chat/) is a list of 3rd party chat model integrations within LangChain! By default, the course with use [GEMINI_API_KEY](https://ai.google.dev/gemini-api/docs/api-key/) because it is both popular and performant. As noted, please ensure that you have an `GEMINI_API_KEY`.\n",
        "\n",
        "Let's check that your `GEMINI_API_KEY` is set and, if not, you will be asked to enter it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "0f9a52c8",
      "metadata": {
        "id": "0f9a52c8"
      },
      "outputs": [],
      "source": [
        "%%capture --no-stderr\n",
        "!pip install -q langchain_google_genai langchain_core langchain_community tavily-python"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain_google_genai import ChatGoogleGenerativeAI\n",
        "\n",
        "from google.colab import userdata\n",
        "GEMINI_API_KEY = userdata.get('GEMINI_API_KEY')\n",
        "llm = ChatGoogleGenerativeAI(\n",
        "    model=\"gemini-1.5-flash\",\n",
        "    api_key=GEMINI_API_KEY,\n",
        "    temperature=0\n",
        ")\n"
      ],
      "metadata": {
        "id": "Ch7HciDZXh3F"
      },
      "id": "Ch7HciDZXh3F",
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "result  = llm.invoke(\"Who won 2024 US presidential ellection?\")\n",
        "result"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "KKnOnfj3YZYT",
        "outputId": "e5695af8-8f9d-47c4-c5ed-38c28164bd07"
      },
      "id": "KKnOnfj3YZYT",
      "execution_count": 14,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "AIMessage(content=\"The 2024 US presidential election has not yet happened. The election is scheduled for **Tuesday, November 5, 2024**. \\n\\nIt's important to rely on credible news sources for information about the election as it gets closer. \\n\", additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-c1c29c12-f3b6-4252-adbe-d0bb8557656f-0', usage_metadata={'input_tokens': 13, 'output_tokens': 54, 'total_tokens': 67, 'input_token_details': {'cache_read': 0}})"
            ]
          },
          "metadata": {},
          "execution_count": 14
        }
      ]
    },
    {
      "cell_type": "markdown",
      "id": "28450d1b",
      "metadata": {
        "id": "28450d1b"
      },
      "source": [
        "Chat models in LangChain have a number of [default methods](https://python.langchain.com/v0.2/docs/concepts/#runnable-interface). For the most part, we'll be using:\n",
        "\n",
        "* `stream`: stream back chunks of the response\n",
        "* `invoke`: call the chain on an input\n",
        "\n",
        "And, as mentioned, chat models take [messages](https://python.langchain.com/v0.2/docs/concepts/#messages) as input. Messages have a role (that describes who is saying the message) and a content property. We'll be talking a lot more about this later, but here let's just show the basics."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "b1280e1b",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "b1280e1b",
        "outputId": "040dbd0b-5e22-4044-b9a1-3fc7f55394a5"
      },
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "AIMessage(content='You\\'re in the right place to learn about LangChain! Here\\'s a breakdown of how you can get started:\\n\\n**1. The Basics:**\\n\\n* **Official Documentation:** The best place to start is the LangChain documentation: [https://langchain.readthedocs.io/en/latest/](https://langchain.readthedocs.io/en/latest/)\\n* **Tutorials:** LangChain has a great collection of tutorials that walk you through building different types of applications: [https://langchain.readthedocs.io/en/latest/](https://langchain.readthedocs.io/en/latest/)\\n* **Example Projects:** Explore the LangChain GitHub repository for example projects that demonstrate various use cases: [https://github.com/langchain-ai/langchain](https://github.com/langchain-ai/langchain)\\n\\n**2. Key Concepts:**\\n\\n* **Chains:** LangChain\\'s core concept. Chains are sequences of components that work together to achieve a specific task.\\n* **LLMs (Large Language Models):** The brains of LangChain applications. You\\'ll use LLMs like GPT-3, Jurassic-1 Jumbo, or others to generate text, translate languages, write different kinds of creative content, and answer your questions in an informative way.\\n* **Prompts:** The instructions you give to the LLM. Crafting effective prompts is crucial for getting the desired output.\\n* **Memory:** LangChain allows you to store and retrieve information from previous interactions, making your applications more context-aware.\\n* **Agents:**  LangChain agents can interact with external tools and APIs, expanding the capabilities of your applications.\\n\\n**3. Hands-on Learning:**\\n\\n* **Code Examples:**  The LangChain documentation and tutorials provide plenty of code examples to get you started.\\n* **Build Your Own Projects:**  Start with simple projects and gradually increase complexity.  \\n* **Community Support:** Join the LangChain community on Discord or GitHub for help and discussions:\\n    * Discord: [https://discord.gg/langchain](https://discord.gg/langchain)\\n    * GitHub: [https://github.com/langchain-ai/langchain](https://github.com/langchain-ai/langchain)\\n\\n**4. Resources:**\\n\\n* **LangChain Blog:** Stay up-to-date with the latest news and developments: [https://www.langchain.dev/](https://www.langchain.dev/)\\n* **YouTube Tutorials:** Search for \"LangChain tutorials\" on YouTube for video explanations and demonstrations.\\n\\n**5. Choose Your Path:**\\n\\n* **Beginner:** Start with the basic tutorials and build simple applications.\\n* **Intermediate:** Explore more advanced concepts like agents and memory.\\n* **Advanced:** Contribute to the LangChain community by developing new chains or tools.\\n\\nLet me know if you have any specific questions or want to explore a particular aspect of LangChain. I\\'m here to help! \\n', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-dbaea432-33a9-4ef2-aa7d-1e43b2618bfc-0', usage_metadata={'input_tokens': 39, 'output_tokens': 633, 'total_tokens': 672, 'input_token_details': {'cache_read': 0}})"
            ]
          },
          "metadata": {},
          "execution_count": 7
        }
      ],
      "source": [
        "from langchain_core.messages import HumanMessage, AIMessage\n",
        "\n",
        "# Create a message\n",
        "# Message list\n",
        "messages = [\n",
        "    HumanMessage(content=\"Hi\", name=\"Human Student\"),\n",
        "    AIMessage(content='Hi! How can I help you today? \\n', name=\"AI Assistant\"),\n",
        "    HumanMessage(content=\"What is LangChain?\", name=\"Human Student\"),\n",
        "    AIMessage(content='LangChain is a framework for developing applications powered by language models.', name=\"AI Assistant\"),\n",
        "    HumanMessage(content=\"How can I learn\", name=\"Human Student\"),\n",
        "    ]\n",
        "\n",
        "# Invoke the model with a list of messages\n",
        "llm.invoke(messages)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "cac73e4c",
      "metadata": {
        "id": "cac73e4c"
      },
      "source": [
        "We get an `AIMessage` response. Also, note that we can just invoke a chat model with a string. When a string is passed in as input, it is converted to a `HumanMessage` and then passed to the underlying model.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "582c0e5a",
      "metadata": {
        "id": "582c0e5a"
      },
      "source": [
        "The interface is consistent across all chat models and models are typically initialized once at the start up each notebooks.\n",
        "\n",
        "So, you can easily switch between models without changing the downstream code if you have strong preference for another provider.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3ad0069a",
      "metadata": {
        "id": "3ad0069a"
      },
      "source": [
        "## Search Tools\n",
        "\n",
        "You'll also see [Tavily](https://tavily.com/) in the README, which is a search engine optimized for LLMs and RAG, aimed at efficient, quick, and persistent search results. As mentioned, it's easy to sign up and offers a generous free tier. Some lessons (in Module 4) will use Tavily by default but, of course, other search tools can be used if you want to modify the code for yourself."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "id": "52d69da9",
      "metadata": {
        "id": "52d69da9"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "from google.colab import userdata\n",
        "TAVILY_API_KEY = userdata.get('TAVILY_API_KEY')\n",
        "os.environ[\"TAVILY_API_KEY\"] = userdata.get('TAVILY_API_KEY')\n",
        "\n",
        "from langchain_community.tools.tavily_search import TavilySearchResults\n",
        "tavily_search = TavilySearchResults(max_results=3)\n",
        "search_docs = tavily_search.invoke(\"Who won 2024 US presidential ellection?\")"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "search_docs"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "JWzZ6zAvb2Fv",
        "outputId": "c25d7fa9-cdf6-41c6-f7db-acfc7c54c944"
      },
      "id": "JWzZ6zAvb2Fv",
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[{'url': 'https://www.bbc.com/news/election/2024/us/results',\n",
              "  'content': 'US Presidential Election Results 2024 - BBC News Close menu BBC News Kamala Harris of the Democrat party has 0 electoral college votes. Donald Trump of the Republican party has 0 electoral college votes. Kamala Harris of the Democrat party has 158,810 votes (38.4%) Donald Trump of the Republican party has 249,225 votes (60.2%) US presidential election results 2024 US election 2024 Voting in some states is particularly hard to predict, with polls showing they could be won by the Republicans or the Democratic party. The battleground states that could decide the 2024 presidential election are: Voters in 11 states will also elect a governor. US election polls: Who is ahead - Harris or Trump? US election 2024 About the BBC'},\n",
              " {'url': 'https://www.270towin.com/',\n",
              "  'content': 'Headlines\\nGeorge Santos Expelled from House of Representatives\\n311 members voted to remove the New York Republican from office\\nCeleste Maloy Sworn In; U.S. House Back at Full Strength\\nThe Utah Republican won a special election earlier this month to fill the vacancy created when Chris Stewart resigned\\nCalifornia Democratic Rep. Anna Eshoo to Retire Next Year\\nFirst elected in 1992, she will complete her 16th term in 2024\\nOverview and Live Results: Utah 2nd Congressional District Special Election\\n The lone vacancy in the U.S. House will be filled by the winner, who will complete the term of Chris Stewart (R), who resigned in September\\nCalifornia Democratic Rep. Tony CÃ¡rdenas Not Seeking Reelection\\nHe represents a deep blue district in the Los Angeles area\\nRelated Content\\nUsing 2024 electoral votes by state\\n© 2023 Electoral Ventures LLC. You are viewing:\\nMap :\\nAs of Nov. 6, 2023 Details >>\\nPlace the map on your website with this code.\\n Follow\\n2024 Presidential Election Interactive Map\\nIt will take 270 electoral votes to win the 2024 presidential election. Use the buttons below the map to share your forecast or embed it into a web page.\\n'},\n",
              " {'url': 'https://www.cbsnews.com/news/donald-trump-win-presidency-2024/',\n",
              "  'content': \"Donald Trump wins election in historic comeback after 2020 loss, indictments and bruising campaign - CBS News Donald Trump wins election in historic comeback after 2020 loss, indictments and bruising campaign Trump was projected by CBS News to have won the battleground states of North Carolina, Georgia, Pennsylvania and Wisconsin — surpassing the electoral vote threshold of 270 by 6 votes with a total of 276. At 78, Trump is the oldest person to be elected president — breaking the record held by President Biden, who withdrew from the 2024 presidential race in July amid questions about his age and competency. Olivia Rinaldi is a campaign digital reporter at CBS News covering former President Donald Trump's 2024 presidential campaign.\"}]"
            ]
          },
          "metadata": {},
          "execution_count": 16
        }
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12.3"
    },
    "colab": {
      "provenance": []
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
